<?php
/**
 * (海外仓-谷仓)（海外仓配-出库单）
 */
namespace App\Logic\Plat\Rakuten\Overseas\GuCang\Order;

use App\Logic\Plat\Rakuten\Overseas\GuCang\Inventory\OverSeasInventory;
use App\Logic\Plat\Rakuten\Overseas\GuCang\Product\OverseasProduct;
use App\Logic\Plat\Rakuten\Overseas\GuCang\RakutenOverseasClient;
use App\Models\CustomerDelivery\CustomerDelivery;
use App\Models\CustomerDelivery\CustomerDeliveryDetail;
use App\Models\CustomerDelivery\CustomerDeliveryLogistics;
use App\Models\CustomerDelivery\CustomerLogs;
use App\Models\CustomerDelivery\CustomerOrder;
use App\Models\Product\ProductSku;
use App\Models\Rakuten\RakutenLogs;
use App\Models\Rakuten\RakutenOrder;
use Illuminate\Support\Facades\DB;

class OverseasOrder extends RakutenOverseasClient{

    const get_order_list = 'public_open/order/get_order_list'; //获取出库订单
    const get_lite_order_list = 'public_open/order/get_lite_order_list'; //获取精简订单列表
    const create_order = 'public_open/order/create_order'; //创建出库订单
    const modify_order = 'public_open/order/modify_order'; //更新出库订单
    const cancel_order = 'public_open/order/cancel_order'; //取消出库订单
    const get_order_by_ref_code = 'public_open/order/get_order_by_ref_code'; //获取单号(乐天订单号)

    /**
     * 订单状态
     * @var string[]
     */
    public static $orderStatus = [
        'W' => '待发货',
        'D' => '已发货',
        'N' => '异常订单',
        'P' => '问题件',
        'X' => '废弃'
    ];

    public static function getReferenceOrder($orderId = null){
        $apiParams = [
            'reference_no' => $orderId,
        ];

        $res = self::getRequest(self::get_order_by_ref_code,$apiParams);
        if ($res) {
            if ($res->data) {
                return $res->data;
            }else{
                return [];
            }
        }else{
            return [];
        }
    }

    /**
     * 获取出库订单
     * @param null $orderCode
     * @param array $orderCodeArr
     * @param null $orderStatus
     * @param null $startTime
     * @param null $endTime
     * @return array
     */
    public static function getOrderList($orderCode = null, $orderCodeArr = [], $orderStatus = null, $startTime = null, $endTime = null){

        $apiParams = [
            //'order_status' => $orderStatus,
            'page' => 1,
            'pageSize' => 1
        ];

        //订单号(谷仓单号)
        if ($orderCode != 'null') {
            $apiParams['order_code'] = $orderCode;
        }else{
            $apiParams['modify_date_from'] = date('Y-m-d H:i:s', time() - 3600); //1小时
            $apiParams['modify_date_to'] = date('Y-m-d H:i:s', time());
        }
        //订单号数组(批量)
        if ($orderCodeArr) {
            $apiParams['order_code_arr'] = $orderCodeArr;
        }
        //请求开始时间
        if ($startTime != 'null' && strtotime($startTime)) {
            $apiParams['modify_date_from'] = $startTime. ' 00:00:00';
        }
        //请求结束时间
        if ($endTime != 'null' && strtotime($endTime)) {
            $apiParams['modify_date_to'] = $endTime. ' 23:59:59';
        }

        $res = self::getRequest(self::get_order_list,$apiParams);
        if ($res->message == 'Success') {
            //执行翻页,数据合并(数组集合)
            return self::getResultList($res,self::get_order_list,$apiParams);
        }else{
            //日志
            RakutenLogs::logs(RakutenLogs::$overseasOrder,
                json_encode($res,JSON_UNESCAPED_UNICODE),
                json_encode($apiParams,JSON_UNESCAPED_UNICODE)
            );
            return [];
        }
    }

    /**
     * 获取出库精简订单（简化数据）
     * @param null $orderCode
     * @param array $orderCodeArr
     * @param null $orderStatus
     * @param null $startTime
     * @param null $endTime
     * @return array
     */
    public static function getLiteOrderList($orderCode = null, $orderCodeArr = [], $orderStatus = null, $startTime = null, $endTime = null){
        $modifyDateFrom = $startTime ?? date('Y-m-d H:i:s', strtotime('2024-08-30 00:00:00'));
        $modifyDateTo = $endTime ?? date('Y-m-d H:i:s', time());
        $apiParams = [
            'order_code' => $orderCode,
            'order_code_arr' => $orderCodeArr,
            'order_status' => $orderStatus,
            'modify_date_from' => $modifyDateFrom, //修改开始时间
            'modify_date_to' => $modifyDateTo, //修改结束时间
            'page' => 1,
            'pageSize' => 100
        ];

        $res = self::getRequest(self::get_lite_order_list,$apiParams);
        if ($res->message == 'Success') {
            //执行翻页,数据合并(数组集合)
            return self::getResultList($res,self::get_lite_order_list,$apiParams);
        }else{
            //日志
            RakutenLogs::logs(RakutenLogs::$overseasOrder,
                json_encode($res,JSON_UNESCAPED_UNICODE),
                json_encode($apiParams,JSON_UNESCAPED_UNICODE)
            );
            return [];
        }
    }

    /**
     * 创建海外仓订单
     * @param $customerDeliveryOrder
     * @param $deliveryOrderNo
     * @param $platAccountId
     * @return bool
     */
    public static function createOrder($customerDeliveryOrder,$deliveryOrderNo,$platAccountId){

        $overseasFlag = false;
        if(!$customerDeliveryOrder) return false;
        if(!$customerDeliveryOrder->detail) return false; //订单明细
        if(!$customerDeliveryOrder->receiver) return false; //订单地址
        if(!$deliveryOrderNo && !$platAccountId) return false;

        //DB::beginTransaction();
        //try{
            //验证：谷仓订单sku明细
            $customerDeliveryDetails = CustomerDeliveryDetail::query()
                ->where('delivery_order_no', $deliveryOrderNo)
                ->where('account_id', $platAccountId)
                ->get();
            if ($customerDeliveryDetails->isEmpty()) return false;
            $overseasOrderItem = [];
            foreach ($customerDeliveryDetails as $key => $val) {
                $overseasOrderItem[$key]['product_sku'] = ProductSku::getValueById($val->psku_id,'psku_code');
                $overseasOrderItem[$key]['quantity'] = $val->apply_num ?? 0;
            }
            if (!$overseasOrderItem) return false;

            /***特定sku的发货方式（JP_NEKO_POSU）****/
            $orderItemSku = array_column($overseasOrderItem,'product_sku'); //订单中的sku
            $filterSkuArr = ['AM04207','AM04208','AM05112','AM05111','AM05116','AM05115']; //指定用于JP_NEKO_POSU发货方式的sku
            $commonValues = array_intersect($orderItemSku, $filterSkuArr); //两个数组中是否存在相同的sku
            $filterStatus = false; //个别sku指定的发货方式(是否可用)
            if (count($commonValues) > 0) {
                $filterStatus = true;
            }
            /***特定sku的发货方式（JP_NEKO_POSU）****/

            //1.获取谷仓产品,并计算物流产品代码 (最便宜实惠的发货物流方式)
            $productSkuArr = array_column($overseasOrderItem, 'product_sku'); //商品编码(多个):["sku1","sku2","sku3"]
            $overseasProducts = OverseasProduct::getProductSkuList(null, $productSkuArr);
            $shippingMethod = [];
            if ($overseasProducts->message) {
                if ($overseasProducts->message == 'Success') {
                    if ($overseasProducts->data) {
                        $skuArr = array_column($overseasProducts->data, 'product_sku');
                        //2.获取谷仓物流产品代码 (发货方式以及物流价格)
                        $overseasProducts1 = OverSeasInventory::getCalculateDeliveryFee(self::WAREHOUSE_CODE, $skuArr, $customerDeliveryOrder);
                        foreach ($overseasProducts1->data as $key => $val) {
                            if ($filterStatus == true) { //JP_NEKO_POSU发货方式是否可用。(个别sku存在于订单之内，则启用)
                                if(!in_array($val->sm_code, ['JP_SAGAWA_KYUUBIN','JP_TAK_KYUUBIN','JP_NEKO_POSU'])) continue;
                            }else{
                                if(!in_array($val->sm_code, ['JP_SAGAWA_KYUUBIN','JP_TAK_KYUUBIN'])) continue;
                            }
                            //if ($val->sm_code == 'JP_NEKO_POSU') continue; //过滤,物流产品代码(JP_黑猫本地小包)
                            //if ($val->sm_code == 'JP_TAK_KYUUBIN_MT') continue; //过滤,物流产品代码(JP_黑猫宅急便多箱)
                            //if ($val->sm_code == 'JP_FBA_LOCAL') continue; //过滤,物流产品代码(JP_本地FBA)

                            $shippingMethod[$val->sm_code] = $val->total;
                        }
                    }
                }
            }
            if (!$shippingMethod) return false;
            $minTotal = min($shippingMethod); //最快最优惠的价格
            $smCode = array_search($minTotal, $shippingMethod); //最快最优惠的物流产品代码(发货方式)

            //3.订单发货
            $address1 = $customerDeliveryOrder->receiver->address ?? '';
            $address2 = ''; //(地址长度限制：50字符，地址1超过50字符，超过的部分，要拆解到地址2)
            if (strlen($customerDeliveryOrder->receiver->address) > 50) {
                $str = $address1;
                $address1 = mb_substr($str, 0, 50, 'UTF-8');
                $address2 = mb_substr($str, 50, null, 'UTF-8');
            }

            $apiParams = [
                'reference_no' => $deliveryOrderNo,
                'platform' => self::PLATFORM, //平台
                'shipping_method' => $smCode, //物流产品代码(发货方式)
                'warehouse_code' => self::WAREHOUSE_CODE, //配送仓库代码
                'wp_code' => self::WP_CODE, //物理仓
                'country_code' => $customerDeliveryOrder->receiver->country, //收件人国家/地区
                'province' => $customerDeliveryOrder->receiver->state, //省/州
                'city' => $customerDeliveryOrder->receiver->city, //城市
                'address1' => $address1, //地址1
                'address2' => $address2, //地址2
                'name' => $customerDeliveryOrder->receiver->receiver, //收件人名
                'zipcode' => $customerDeliveryOrder->receiver->postcode, //邮编
                'phone' => $customerDeliveryOrder->receiver->phone, //收件人电话(当platform为AMAZON时，可以由此分解分机号(cell_phone)参数。)
                'verify' => 1, //是否直接审核,审核通过之后，不可编辑,默认值: 0 (0:新建不审核(草稿状态) 1:新建并审核)
                'payment_time' => $customerDeliveryOrder->order_at, //付款时间 (格式必须为 YYYY-MM-DD HH:MM:SS，例如：2021-10-01 22:12:01)
                'order_desc' => '', //订单备注
                'items' => $overseasOrderItem,
                'estimated_arrival_date' => date('Y-m-d', time() + (60 * 60 * 24)), //预计到货日期(物流产品支持则填写， 格式例如：2021-03-01)
                'distributor_type' => 0, //配送商(0:谷仓合作物流 1:客户物流（谷仓交运） 2:客户物流（自提）)
                'page' => 1,
                'pageSize' => 10
            ];
            if ($smCode == 'JP_NEKO_POSU') { //JP_NEKO_POSU发货方式,不需要指定到货日期
                unset($apiParams['estimated_arrival_date']);
            }

            //创建海外仓出库订单
            $res = self::getRequest(self::create_order, $apiParams);
            if ($res->message == 'Success') {
                $orderCode = $res->order_code ?? '';

                $customerDeliveryOrder->plat_sync_status = 2;
                $customerDeliveryOrder->plat_sync_at = date('Y-m-d H:i:s');
                $customerDeliveryOrder->save();

                CustomerDeliveryDetail::query()
                    ->where('delivery_type',2)
                    ->where('delivery_order_no',$deliveryOrderNo)
                    ->update([
                        'overseas_order_id' => $orderCode
                    ]);

                $overseasFlag = true;
            }else{
                //异常日志
                CustomerLogs::logs(CustomerLogs::$overseasInboundOrder,'海外仓发货(上传平台订单)',$res->message,$deliveryOrderNo);
                $overseasFlag = false;
            }


            return $overseasFlag;

        //    DB::commit();
        //}catch (\Exception $e){
        //    RakutenLogs::logs(RakutenLogs::$overseasOrderError, json_encode($e->getMessage(),JSON_UNESCAPED_UNICODE));
        //
        //    report($e);
        //    DB::rollBack();
        //    return ['status' => false, 'message' => $e->getMessage()];
        //}
    }


    /**
     * 更新订单
     * @param array $orderIds
     * @return array|bool
     */
    /*public static function modifyOrder($orderIds = []){
        dd('stop!');
        if (!$orderIds) dd('no order!');

        //rakuten订单
        $query = RakutenOrder::query();
        //$query->where('order_progress', 300); //乐天订单状态：待发货
        //$query->where('overseas_sync', 1); //海外仓状态：未同步
        $query->where('order_datetime', '>=', strtotime('2024-01-24 00:00:00'));
        if($orderIds){
            $query->whereIn('order_id', $orderIds);
        }
        $query->orderBy('id');
        $rakutenOrders = $query->get();
        if (!$rakutenOrders) dd('over!');

        DB::beginTransaction();
        try{
            foreach ($rakutenOrders as $rakutenOrder){
                if (!$rakutenOrder->rakuten_orders_items) continue; //rakuten订单明细
                if (!$rakutenOrder->rakuten_orders_address) continue; //rakuten订单地址
                $orderNo = $rakutenOrder->order_id; //rakuten订单号
                $gucangOrderId = $rakutenOrder->gucang_order_id; //海外仓(谷仓)订单号

                //验证：乐天订单sku明细
                $overseasOrderItem = [];
                foreach ($rakutenOrder->rakuten_orders_items as $key => $val){
                    //$pskuId = ProductRakutenSku::getValueByCode($val->platform_sku, 'psku_id');
                    $pskuId = ProductSku::getValueByCode($_v->variant_id, 'id');
                    if (!$pskuId) continue;
                    $overseasOrderItem[$key]['product_sku'] = $val->variant_id;
                    $overseasOrderItem[$key]['quantity'] = $val->units ?? 0;
                }
                //验证：比对谷仓订单与乐天订单的产品数量
                if (!$overseasOrderItem) continue;
                $overseasOrderItemsCount = count($overseasOrderItem);
                $rakutenOrderItemsCount = count($rakutenOrder->rakuten_orders_items);
                if ($overseasOrderItemsCount != $rakutenOrderItemsCount) continue;

                //1.获取谷仓产品
                $productSkuArr = array_column($overseasOrderItem,'product_sku'); //商品编码(多个):["sku1","sku2","sku3"]
                $overseasProducts = OverseasProduct::getProductSkuList(null,$productSkuArr);

                //验证：计算物流产品代码 (最便宜实惠的发货物流方式)
                $shippingMethod = [];
                if ($overseasProducts->message == 'Success' && $overseasProducts->data) {
                    $skuArr = array_column($overseasProducts->data,'product_sku');
                    //2.获取谷仓物流产品代码 (发货方式)
                    $overseasProducts = OverSeasInventory::getCalculateDeliveryFee(self::WAREHOUSE_CODE,$skuArr,$rakutenOrder);
                    foreach ($overseasProducts->data as $key => $val){
                        if ($val->sm_code == 'JP_NEKO_POSU') continue; //过滤,物流产品代码(JP_黑猫本地小包)
                        if ($val->sm_code == 'JP_TAK_KYUUBIN_MT') continue; //过滤,物流产品代码(JP_黑猫宅急便多箱)
                        $shippingMethod[$val->sm_code] = $val->total;
                    }
                }
                if (!$shippingMethod) continue;
                $minTotal = min($shippingMethod); //最快最优惠的价格
                $smCode = array_search($minTotal,$shippingMethod); //最快最优惠的物流产品代码(发货方式)

                //3.订单发货
                $apiParams = [
                    'order_code' => $gucangOrderId,
                    'reference_no' => $orderNo,
                    'platform' => self::PLATFORM, //平台
                    'shipping_method' => $smCode, //物流产品代码(发货方式)
                    'warehouse_code' => self::WAREHOUSE_CODE, //配送仓库代码
                    'wp_code' => self::WP_CODE, //物理仓
                    'country_code' => $rakutenOrder->rakuten_orders_address->country_code, //收件人国家/地区
                    'province' => $rakutenOrder->rakuten_orders_address->prefecture, //省/州
                    'city' => $rakutenOrder->rakuten_orders_address->city, //城市
                    'address1' => $rakutenOrder->rakuten_orders_address->address, //地址1(长度限制：50字符，地址1超过50字符，超过的部分，要拆解到地址2)
                    'address2' => '', //地址2
                    'zipcode' => $rakutenOrder->rakuten_orders_address->zip_code, //邮编
                    'name' => $rakutenOrder->rakuten_orders_address->family_name, //收件人名
                    'phone' => $rakutenOrder->rakuten_orders_address->phone_number, //收件人电话(当platform为AMAZON时，可以由此分解分机号(cell_phone)参数。)
                    //'items' => $overseasOrderItem
                    //'verify' => 0, //是否直接审核,审核通过之后，不可编辑,默认值: 0 (0:新建不审核(草稿状态) 1:新建并审核)
                    //'payment_time' => date('Y-m-d H:i:s', $rakutenOrder->order_datetime), //付款时间 (格式必须为 YYYY-MM-DD HH:MM:SS，例如：2021-10-01 22:12:01)
                    //'order_desc' => '', //订单备注
                    //'estimated_arrival_date' => '2024-07-31', //预计到货日期(物流产品支持则填写， 格式例如：2021-03-01)
                    //'distributor_type' => 0, //配送商(0:谷仓合作物流 1:客户物流（谷仓交运） 2:客户物流（自提）)
                ];

                //创建海外仓出库订单
                $res = self::getRequest(self::modify_order,$apiParams);
                if ($res->message == 'Success') {
                    return true;
                }else{
                    //日志
                    RakutenLogs::logs(RakutenLogs::$overseasOrder,
                        json_encode($res,JSON_UNESCAPED_UNICODE),
                        json_encode($apiParams,JSON_UNESCAPED_UNICODE),
                        json_encode([$orderNo])
                    );
                    return false;
                }
            }

            DB::commit();
            return ['status' => true, 'message' => '操作成功'];
        }catch (\Exception $e){
            report($e);
            DB::rollBack();
            return ['status' => false, 'message' => $e->getMessage()];
        }
    }*/

    /**
     * 取消订单
     * @param $orderCode
     * @return bool
     */
    /*public static function cancelOrder($orderCode){
        $apiParams = [
            'order_code' => $orderCode, //订单号
            'reason' => '' //取消原因
        ];
        $res = self::getRequest(self::cancel_order,$apiParams);

        $requestStatus = false;
        if ($res->message == 'Success') {
            $requestStatus = true;
            return $requestStatus;
        }else{
            //日志
            RakutenLogs::logs(RakutenLogs::$overseasOrder,
                json_encode($res,JSON_UNESCAPED_UNICODE),
                json_encode($apiParams,JSON_UNESCAPED_UNICODE)
            );
            return $requestStatus;
        }
    }*/

    /**
     * 海外仓(谷仓)已发货订单
     * @param null $orderId
     * @param null $startTime
     * @param null $endTime
     */
    public static function updateOrderInfo($orderId = null,$startTime = null,$endTime = null){

        $overseasOrderList = self::getOrderList($orderId,[],'D',$startTime,$endTime);
        if ($overseasOrderList) {
            foreach ($overseasOrderList as $key => $val){
                if ($val->order_status != 'D') continue;

                //谷仓订单号、erp实际发货订单号、erp订单号
                $orderCode = $val->order_code; //谷仓订单号
                $deliveryOrderNo = $val->reference_no; //erp实际发货订单号
                $customerDeliveryDetail = CustomerDeliveryDetail::query()->where('delivery_order_no',$deliveryOrderNo)->first();
                if (!$customerDeliveryDetail) continue;
                $orderNo = $customerDeliveryDetail->order_no ?? ''; //erp订单号
                if (!$orderNo) continue;

                //物流公司编码
                $shippingMethod = $val->shipping_method;
                $rakutenCompany = [
                    'JP_SAGAWA_KYUUBIN' => 1002,  //JP_佐川急便(佐川急便)
                    'JP_TAK_KYUUBIN' => 1001,     //JP_黑猫宅急便(大和运输)
                    'JP_NEKO_POSU' => 1001,       //JP_黑猫本地小包(大和运输)
                    'JP_TAK_KYUUBIN_MT' => 1001   //JP_黑猫宅急便多箱(大和运输)
                ];
                $deliveryCompanyCode = 1000; //默认物流(其他)
                $rakutenCompanyFlag = array_key_exists($shippingMethod,$rakutenCompany);
                if ($rakutenCompanyFlag) {
                    $deliveryCompanyCode = $rakutenCompany[$shippingMethod];
                }

                //物流发货产品
                $sellerSkus = [];
                if($val->items) {
                    foreach ($val->items as $itemKey => $_item) {
                        $sellerSkus[$itemKey]['psku_id'] = ProductSku::getValueByCode($_item->product_sku,'id');
                        $sellerSkus[$itemKey]['quantity'] = $_item->quantity ?? 0;
                    }
                }
                if (!$sellerSkus) continue;

            // DB::beginTransaction();
            // try{
                //1.更新发货单
                foreach ($sellerSkus as $index => $sku) {
                    //发货明细(物流状态同步)
                    CustomerDeliveryDetail::query()
                        ->where('delivery_order_no',$deliveryOrderNo)
                        ->where('psku_id',$sku['psku_id'])
                        ->update([
                            'tracking_no'       => $val->tracking_no,
                            'delivered_at'      => $val->date_shipping,
                            'arrived_at'        => $val->estimated_arrival_date,
                            'overseas_order_id' => $orderCode,
                            'sync_status'       => CustomerDeliveryDetail::SYNC_STATUS_YES, //平台物流追踪号同步 (0:未同步 1:已同步)
                            'logistics_type'    => $shippingMethod,
                            'delivery_company'  => $deliveryCompanyCode ?? 1000,
                            'ship_num'          => $sku['quantity'], //发货数量
                            'status'            => CustomerDeliveryDetail::STATUS_DELIVERY_YES, //已发货
                        ]);
                }

                //验证,更新发货订单(发货单状态、订单同步状态)
                $deliveryDetailStatusArr = CustomerDeliveryDetail::query()
                    ->where('delivery_order_no',$deliveryOrderNo)
                    ->pluck('status')
                    ->toArray();
                if($deliveryDetailStatusArr) {
                    $status = CustomerDeliveryDetail::extractStatus($deliveryDetailStatusArr); //订单状态
                    if ($customerDeliveryDetail->delivery) {
                        $customerDeliveryDetail->delivery->update([
                            'status' => $status,  //发货单状态
                            'plat_sync_status' => 2, //已上传至平台
                            'plat_sync_at' => date('Y-m-d H:i:s', time())
                        ]);
                    }
                }
                //更新发货物流
                $deliveryLogistics = CustomerDeliveryLogistics::query()->firstOrNew(['order_no' => $orderNo]);
                $deliveryLogistics->tracking_no = $val->tracking_no;
                $deliveryLogistics->delivered_at = $val->date_shipping;
                $deliveryLogistics->arrived_at = $val->estimated_arrival_date;
                $deliveryLogistics->save();

                //2.更新客户订单
                $customerOrder = CustomerOrder::query()->where('order_no',$orderNo)->first();
                if ($customerOrder) {
                    //更新客户订单明细
                    if ($customerOrder->detail) {
                        $customerOrder->detail()->update([
                            'overseas_order_id' => $orderCode,
                            'sync_status' => CustomerOrder::SYNC_YES //第三方平台(物流)信息已同步
                        ]);

                        $customerOrder->overseas_order_id = $orderCode;
                        $customerOrder->sync_status = CustomerOrder::SYNC_YES; //第三方平台(物流)信息已同步
                        $customerOrder->save();
                        //DB::commit();
                    }
                }

                //3.更新rakuten订单
                $rakutenOrder = RakutenOrder::query()->where('order_id',$orderNo)->first();
                if ($rakutenOrder) {
                    //更新rakuten订单明细
                    if ($rakutenOrder->rakuten_orders_items) {
                        $rakutenOrder->rakuten_orders_items()->update([
                            'overseas_order_id' => $orderCode,
                            'overseas_sync' => RakutenOrder::OVERSEAS_SYNC_YES //同步至海外仓(谷仓)：1未同步，2已同步，3同步异常
                        ]);

                        $rakutenOrder->overseas_order_id = $orderCode;
                        $rakutenOrder->overseas_sync = RakutenOrder::OVERSEAS_SYNC_YES; //同步至海外仓(谷仓)：1未同步，2已同步，3同步异常
                        $rakutenOrder->save();
                        //DB::commit();
                    }
                }

            //     DB::commit();
            // }catch (\Exception $e){
            //     DB::rollBack();
            //     report($e);
            // }

            }
        }
    }


}
